using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using Castle.Windsor;
using Castle.Facilities.NHibernateIntegration;
using NHibernate;
using Castle.MicroKernel.Facilities;

namespace Redboil.Bfp.Core {
    public class SessionWebModule : IHttpModule {
        protected static readonly String sessionKey = "NHibernateSession";

        /// <summary>
        /// Initializes a new instance of the <see cref="SessionWebModule"/> class.
        /// </summary>
        public SessionWebModule() {
            
        }

        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        public void Init(HttpApplication httpApplication) {
            httpApplication.BeginRequest += new EventHandler(OnBeginRequest);
            httpApplication.EndRequest += new EventHandler(OnEndRequest);
        }

        /// <summary>
        /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
        /// </summary>
        public void Dispose() {

        }

        private void OnBeginRequest(object sender, EventArgs e) {
            #region For test the container either normaly initialized.
            //Castle.Windsor.Configuration.Interpreters.XmlInterpreter interpreter;
            //WindsorContainer windsor;
            //Castle.MicroKernel.IKernel kernel;
            //interpreter = new Castle.Windsor.Configuration.Interpreters.XmlInterpreter("Castle.config");
            //windsor = new WindsorContainer(interpreter);
            //kernel = windsor.Kernel;
            #endregion

            ISessionManager sessionManager = Container.Instance.Resolve<ISessionManager>();
            HttpContext.Current.Items.Add(sessionKey, sessionManager.OpenSession());
        }

        private void OnEndRequest(object sender, EventArgs e) {
            ISession session = (ISession)HttpContext.Current.Items[sessionKey];
            if (session != null) {
                session.Dispose();
            }
        }
    }
}